from boot import os, Callable, DB_ROOT_DIR, get_json_config, set_json_config, logger, Signal
import shutil
from datetime import datetime
from threading import Thread
import time


def calculate_days_between_dates(last_date) -> int:
    try:
        # 1.获取当前日期和时间
        current_datetime = str(datetime.now().strftime('%Y-%m-%d'))
        # 将日期字符串转换为 datetime 对象
        date_obj1 = datetime.strptime(current_datetime, '%Y-%m-%d')
        date_obj2 = datetime.strptime(last_date, '%Y-%m-%d')
        # 计算两个日期之间的天数差
        delta = date_obj1 - date_obj2
        return abs(delta.days)
    except Exception as e:
        logger.warning(f"计算天数差时出错：{e}")
        return 100


def copy_file_with_timestamp(file_path):
    # 获取文件的目录和文件名
    directory = os.path.dirname(file_path)
    file_name, file_extension = os.path.splitext(os.path.basename(file_path))
    # 获取当前时间的字符串格式
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    # 构造新的文件名
    new_file_name = f"{file_name}{timestamp}{file_extension}"
    new_file_path = os.path.join(directory + "/backup", new_file_name)
    # 复制文件
    shutil.copy(file_path, new_file_path)


def backup_db_thread(db_name: str, update_cycle: int, main_window: object):
    try:
        time.sleep(10)
        config_dict = get_json_config("root")
        last_backup_time = config_dict["local_db"]["last_backup_time"]
        if calculate_days_between_dates(last_backup_time) >= update_cycle:
            # 1.复制数据库文件
            copy_file_with_timestamp(DB_ROOT_DIR + "/" + db_name)
            # 2.更新配置文件
            config_dict["local_db"]["last_backup_time"] = str(datetime.now().strftime('%Y-%m-%d'))
            # 3.更新配置文件时间
            set_json_config("root", config_dict)
            return main_window.sgn_tips_popup.emit("数据库自动备份已完成, 请放心使用", True)
        else:
            return main_window.sgn_tips_popup.emit("数据库安全保障中, 请放心使用", True)
    except Exception as e:
        return main_window.sgn_tips_popup.emit(f"数据库备份失败{e}", False)


def backup_db(db_name: str, update_cycle: int) -> Callable:
    def wrapper(cls) -> Callable:
        def inner(*args, **kwargs):
            # 0.运行窗体
            obj = cls(*args, **kwargs)
            # 1.启动数据库备份线程
            db_t = Thread(target=backup_db_thread, args=(db_name, update_cycle, obj))
            db_t.daemon = True
            db_t.start()
            return obj
        return inner
    return wrapper